package com.rainbow.chat.test.socket;

import com.rainbow.chat.common.ChatUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * @Author: Usher
 * @Description:
 */
public class SocketClientHandler extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
        //直接输出消息
        System.out.println("===> " + s);
        // ChatMsg chatMsg = JSON.parseObject(s, ChatMsg.class);
    }

    /**
     * 心跳检测
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent){
            IdleStateEvent e = (IdleStateEvent) evt;
            switch (e.state()){
                case READER_IDLE:
                    ctx.close();
                    // TODO 重新连接
                    throw new Exception("连接超时");
                case WRITER_IDLE:
                case ALL_IDLE:
                    ctx.writeAndFlush(ChatUtil.getTipMsg("ping"));break;
                default:
                    break;
            }
        }
//        ctx.fireUserEventTriggered(evt);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("error : " + cause.getMessage());
    }
}